package com.wzy.service.reposirory.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wzy.common.base.redis.RedisUtil;
import com.wzy.common.base.result.R;
import com.wzy.service.reposirory.dto.WordsResponse;
import com.wzy.service.reposirory.entity.GlobalWord;
import com.wzy.service.reposirory.entity.UserArticle;
import com.wzy.service.reposirory.entity.UserSentence;
import com.wzy.service.reposirory.entity.UserWord;
import com.wzy.service.reposirory.feign.ScheduleService;
import com.wzy.service.reposirory.service.GlobalWordService;
import com.wzy.service.reposirory.service.UserArticleService;
import com.wzy.service.reposirory.service.UserSentenceService;
import com.wzy.service.reposirory.service.UserWordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuzhengyu
 * @since 2021-04-05
 */
@RestController
@RequestMapping("/user-article")
public class UserArticleController {

    @Autowired
    UserArticleService userArticleService;
    @Autowired
    UserSentenceService userSentenceService;
    @Autowired
    UserWordService userWordService;
    @Autowired
    GlobalWordService globalWordService;

    @Autowired
    ScheduleService scheduleService;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 通过uid来获取指定用户的所有文章
     * @param uid
     * @return
     */
    @GetMapping("/article")
    public R getUserArticleByUid(@RequestParam String uid) {
        List<UserArticle> list = userArticleService.list(Wrappers.<UserArticle>lambdaQuery().eq(UserArticle::getUid, uid));
        return R.ok().data("articleList", list);
    }


    // 用户上传文章
    @PostMapping("/uploadArticle")
    public R getEveryDayWord(String article, String uid) throws Exception {
        return userArticleService.getEveryDayWord(article, uid);

    }

    @PostMapping("article")
    public R createCurrentUserArticle(String uid, String level) throws Exception {
        return userArticleService.createUserArticle(uid, level);
    }


    /**
     * 判断用户是否创建了当天的学习
     * 判断方法是查询当前用户uid 用户文章表中创建时间为当天的文章
     * @param uid
     * @return
     */
    @GetMapping("/current-study")
    public R isCompleteCurrentStudy(String uid) {
        // 当前时间
        //Date date = new Date();
        Calendar zeroDate = Calendar.getInstance();
        zeroDate.set(Calendar.HOUR_OF_DAY, 0);
        zeroDate.set(Calendar.MINUTE, 0);
        zeroDate.set(Calendar.SECOND, 0);

        Calendar endDate = Calendar.getInstance();
        endDate.set(Calendar.HOUR_OF_DAY, 23);
        endDate.set(Calendar.MINUTE, 59);
        endDate.set(Calendar.SECOND, 59);


        List<UserArticle> list = userArticleService.list(Wrappers.<UserArticle>lambdaQuery()
                .ge(UserArticle::getGmtCreate, zeroDate.toInstant())
                .le(UserArticle::getGmtCreate, endDate.toInstant())
                .eq(UserArticle::getUid, uid));
        if(list == null || list.size() == 0) {
            return R.ok().data("isCreateArticle", true);
        } else {
            return R.ok().data("i   sCreateArticle", false);
        }

    }


    /**
     * 获取需要复习的文章
     * @param uid
     * @return
     */
    @GetMapping("/current-remind-article")
    public R getCurrentRemindArticle(String uid) {

        Calendar endDate = Calendar.getInstance();
        endDate.set(Calendar.HOUR_OF_DAY, 23);
        endDate.set(Calendar.MINUTE, 59);
        endDate.set(Calendar.SECOND, 59);

        // 获取条件:
        // 1. 下次复习时间小于当前时间
        // 2. 阶段不是完成
        List<UserArticle> list = userArticleService
                .list(Wrappers.<UserArticle>lambdaQuery()
                        .le(UserArticle::getNextReviewTime, endDate)
                        .eq(UserArticle::getUid, uid).ne(UserArticle::getPhases, "完成"));
        return R.ok().data("list", list);
    }

    /**
     * 获取用户当天的单词\句子\文章
     * @param uid
     * @return
     */
    @GetMapping("/user-work")
    public R getUserArticleWork(String uid, String aid, String uaid) {
        List<UserArticle> list = userArticleService.list(Wrappers.<UserArticle>lambdaQuery()
                .eq(UserArticle::getUid, uid).eq(UserArticle::getAid, aid));
        UserArticle userArticle = list.get(0);

        List<UserSentence> userSentences = userSentenceService.list(Wrappers.<UserSentence>lambdaQuery().eq(UserSentence::getUid, uid).eq(UserSentence::getUserArticleId, uaid));
        List<WordsResponse> collect = new ArrayList<>();
        userSentences.forEach(s -> {
            System.out.println(s.getId());
            List<UserWord> userWord = userWordService.list(Wrappers.<UserWord>lambdaQuery().ne(UserWord::getStatus, "掌握").eq(UserWord::getSid, s.getId()));
            userWord.forEach(word -> {
                GlobalWord one = globalWordService.getOne(Wrappers.<GlobalWord>lambdaQuery().eq(GlobalWord::getId, word.getGwid()));
                collect.add(new WordsResponse(word, one));
            });
        });
        return R.ok().data("words", collect).data("article", userArticle).data("sentences", userSentences);
    }

    /**
     * 用户完成文章学习
     * @param uid
     * @param aid
     * @return
     */
    @PostMapping("/article-complete")
    public R completeArticle(String uid, String aid) {
        redisUtil.set(uid + "-"+ aid, "1");
        return R.ok();
    }

    @GetMapping("/article-complete")
    public R getCompleteArticle(String uid, String aid) {
        String s = redisUtil.get(uid + "-" + aid);
        if (s == null) {
            return R.ok().data("isComplete", false);
        } else {
            return R.ok().data("isComplete", true);
        }
    }

    /**
     * 更新文章的phases
     */
    @PutMapping("/article-phases")
    public R updateArticlePhases(String uid, String article) throws ParseException {
        // 找到文章

        UserArticle one = userArticleService.getOne(Wrappers.<UserArticle>lambdaQuery().eq(UserArticle::getUid, uid).eq(UserArticle::getId, article));

        // 获取用户计划
        R sche = scheduleService.getSchedule(uid);
        Map<String, Object> schedule = (Map<String, Object>) sche.getData().get("schedule");
        System.out.println(schedule);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date d1 = simpleDateFormat.parse((String) schedule.get("d1"));
        Date d2 = simpleDateFormat.parse((String) schedule.get("d2"));
        Date d3 = simpleDateFormat.parse((String) schedule.get("d3"));
        Date now = new Date();

        // 判断该文章的阶段,并且进行修改 获取该用户设定的下阶段计划时间
        switch (one.getPhases()) {
            case "":
                // 设置阶段
                one.setPhases("d1");
                // 设置下次复习时间
                one.setNextReviewTime(setNewDate(now, d1));
                break;
            case "d1":
                // 设置阶段
                one.setPhases("d2");
                // 设置下次复习时间
                one.setNextReviewTime(setNewDate(now, d2));

                break;
            case "d2":
                // 设置阶段
                one.setPhases("d3");
                // 设置下次复习时间
                one.setNextReviewTime(setNewDate(now, d3));

                break;
            case "d3":
                // 设置阶段
                one.setPhases("c1");
                // 设置下次复习时间

                now.setDate(now.getDate() + (Integer)schedule.get("c1"));
                one.setNextReviewTime(now);
                break;
            case "c1":
                one.setPhases("c2");
                // 设置下次复习时间
                now.setDate(now.getDate() + (Integer)schedule.get("c2"));
                one.setNextReviewTime(now);
                break;
            case "c2":
                one.setPhases("c3");
                // 设置下次复习时间
                now.setDate(now.getDate() + (Integer)schedule.get("c3"));
                one.setNextReviewTime(now);
                break;
            case "c3":
                one.setPhases("c4");
                // 设置下次复习时间
                now.setDate(now.getDay() + (Integer)schedule.get("c4"));
                one.setNextReviewTime(now);
                break;
            case "c4":
                one.setPhases("完成");
                now.setYear(1);
                one.setNextReviewTime(now);
                break;
        }

        userArticleService.update(one, Wrappers.<UserArticle>lambdaUpdate().eq(UserArticle::getUid, uid).eq(UserArticle::getId,article));


        return R.ok().data("phases", one.getPhases());
    }


    /**
     * 获取nextTime小于当前时间的所有文章
     * @return
     */
    @GetMapping("article-next-time")
    public R getNextTimeArticle() {
        Date now = new Date();
        List<UserArticle> list = userArticleService.list(Wrappers.<UserArticle>lambdaQuery()
                .le(UserArticle::getNextReviewTime, now)
                .ne(UserArticle::getPhases, "完成")
                .ne(UserArticle::getPhases,""));
        List<HashMap<String, String>> collect = list.stream().map(t ->
                new HashMap<String, String>() {{
                    put("id", t.getId().toString());
                    put("nextTime", t.getNextReviewTime().toString());
                    put("uid", t.getUid().toString());
                }}).collect(Collectors.toList());
        return R.ok().data("articles", collect);
    }



    private Date setNewDate(Date old, Date add) {
        Date date = new Date();
        int minutes = old.getMinutes() + add.getMinutes();
        int h = minutes / 60;
        minutes %= 60;
        int hour = old.getHours() + add.getHours() + h;
        date.setHours(hour);
        date.setMinutes(minutes);
        return date;
    }

}

